<template>
  <div class="profile-container">
    <a-page-header title="Profile" sub-title="Manage your personal information"/>
    
    <a-row :gutter="16">
      <!-- 左侧用户信息卡片 -->
      <a-col :xs="24" :sm="24" :md="24" :lg="8" :xl="8">
        <a-card class="user-info-card">
          <div class="user-header">
            <a-avatar :size="100" :src="profileData.avatar || 'https://joeschmoe.io/api/v1/random'"/>
            <div class="user-basic-info">
              <h2>{{ profileData.first_name }} {{ profileData.last_name }}</h2>
              <div class="member-badge">
                <a-tag color="gold">Member</a-tag>
              </div>
            </div>
          </div>
          
          <a-divider/>
          
          <!-- 邀请码信息 -->
          <div class="invitation-code-section">
            <div class="invitation-code-title">
              <h3>My Invitation Code</h3>
            </div>
            <div class="invitation-code-display">
              <template v-if="profileData.invitation_code">
                <div class="code-value">
                  <h2>{{ profileData.invitation_code }}</h2>
                  <a-button type="link" size="small" @click="copyInvitationCode">
                    <template #icon><copy-outlined /></template>
                    Copy
                  </a-button>
                </div>
                
                <!-- 添加邀请链接显示 -->
                <div class="invitation-link-section">
                  <div class="link-header">
                    <h4>Invitation Link</h4>
                    <a-tag color="default" size="small">Share to get rewards</a-tag>
                  </div>
                  <div class="link-value">
                    <p>{{ invitationLink }}</p>
                    <a-button type="default" size="small" @click="copyInvitationLink">
                      <template #icon><copy-outlined /></template>
                      Copy Link
                    </a-button>
                  </div>
                </div>
                
                <!-- <a-button type="link" @click="navigateTo('/user/invitation-code')">
                  Invite Friends to Get Rewards <right-outlined />
                </a-button> -->
              </template>
              <template v-else>
                <div class="empty-code">
                  <p>You don't have an invitation code yet</p>
                  <a-button type="default" size="small" @click="navigateTo('/user/invitation-code')">
                    Get Invitation Code
                  </a-button>
                </div>
              </template>
            </div>
          </div>
          
          <a-divider/>
          
          <!-- 使用 Ant Design Statistic 组件替代自定义样式 -->
          <a-row class="user-stats" :gutter="16">
            <a-col :span="8">
              <a-statistic title="Total Points" :value="profileData.total_score" :value-style="{ color: '#3f8600' }" />
            </a-col>
            <a-col :span="8">
              <a-statistic title="Available Points" :value="profileData.score" />
            </a-col>
            <a-col :span="8">
              <a-badge :count="unreadMessageCount" :offset="[10, 7]" :overflowCount="99">
                <a-statistic title="Messages" :value="messageCount">
                  <template #prefix>
                    <mail-outlined />
                  </template>
                </a-statistic>
              </a-badge>
            </a-col>
          </a-row>
          
          <a-divider/>
          
          <div class="quick-links">
            <h3>Quick Links</h3>
            <a-row :gutter="[16, 16]">
              <a-col :span="8">
                <div class="link-item" @click="navigateTo('/user/orders')">
                  <shopping-outlined />
                  <p>My Orders</p>
                </div>
              </a-col>
              <a-col :span="8">
                <div class="link-item" @click="navigateTo('/user/wishlist')">
                  <star-outlined />
                  <p>My Wishlist</p>
                </div>
              </a-col>
              <!-- <a-col :span="8">
                <div class="link-item" @click="navigateTo('/user/settings')">
                  <setting-outlined />
                  <p>Account Settings</p>
                </div>
              </a-col> -->
              <a-col :span="8">
                <div class="link-item" @click="navigateTo('/user/points')">
                  <wallet-outlined />
                  <p>Points Center</p>
                </div>
              </a-col>
              <a-col :span="8">
                <div class="link-item" @click="navigateTo('/user/coupons')">
                  <tag-outlined />
                  <p>Coupons</p>
                </div>
              </a-col>
              <a-col :span="8">
                <div class="link-item" @click="navigateTo('/user/message')">
                  <bell-outlined />
                  <p>Messages</p>
                </div>
              </a-col>
            </a-row>
          </div>
          
          <a-divider/>
<!--           
          <div class="member-info">
            <h3>会员信息</h3>
            <p>当前积分：{{ profileData.score }}</p>
            <a-button type="primary" block @click="navigateTo('/user/points')">查看积分明细</a-button>
          </div> -->
        </a-card>
      </a-col>
      
      <!-- 右侧个人资料编辑 -->
      <a-col :xs="24" :sm="24" :md="24" :lg="16" :xl="16">
        <a-card title="Edit Personal Information">
          <a-form :model="profileData" :label-col="{ xs: 24, sm: 6, md: 6, lg: 4, xl: 4 }" :wrapper-col="{ xs: 24, sm: 18, md: 18, lg: 18, xl: 18 }">
            <a-form-item label="First Name">
              <a-input v-model:value="profileData.first_name"/>
            </a-form-item>
            
            <a-form-item label="Last Name">
              <a-input v-model:value="profileData.last_name"/>
            </a-form-item>
            
            <a-form-item label="Email">
              <a-input v-model:value="profileData.email" disabled :class="'disabled-input'"/>
            </a-form-item>
            
            <a-form-item label="Phone Number">
              <phone-number-input 
                :initialPhoneNumber="phoneNumber"
                :initialCountryCode="countryCode"
                @update:phoneData="updatePhoneData" 
              />
            </a-form-item>
            
            <a-form-item label="Gender">
              <a-radio-group v-model:value="profileData.gender">
                <a-radio :value="0">Secret</a-radio>
                <a-radio :value="1">Male</a-radio>
                <a-radio :value="2">Female</a-radio>
              </a-radio-group>
            </a-form-item>
            
            <a-form-item label="Birthday">
              <a-date-picker 
                v-model:value="profileData.birthday"
                :valueFormat="'YYYY-MM-DD'"
              />
            </a-form-item>
            
            <a-form-item label="Avatar">
              <div class="avatar-upload">
                <a-avatar :size="80" :src="profileData.avatar || 'https://joeschmoe.io/api/v1/random'"/>
                <a-upload
                  name="avatar"
                  :show-upload-list="false"
                  :action="null"
                  :customRequest="uploadAvatar"
                  :before-upload="beforeUpload"
                >
                  <a-button type="primary" class="ml-10">Change Avatar</a-button>
                </a-upload>
              </div>
            </a-form-item>
            
            <a-form-item :wrapper-col="{ xs: { span: 24, offset: 0 }, sm: { span: 18, offset: 6 }, md: { span: 18, offset: 6 }, lg: { span: 18, offset: 4 }, xl: { span: 18, offset: 4 } }">
              <a-button type="primary" @click="saveProfile">Save Changes</a-button>
              <a-button class="ml-10" @click="resetForm">Reset</a-button>
            </a-form-item>
          </a-form>
        </a-card>
        
        <!-- 个人公告区域 -->
        <a-card class="announcement-card" title="Personal Announcements">
          <div class="announcements-container">
            <div class="announcement-item">
              <notification-outlined />
              <div class="announcement-content">
                <span class="highlight">Invite friends to register</span>，both can get <span class="highlight">{{ currencyUnit }}{{ convertPrice(INVITE_BONUS) }}</span> coupon
                <template v-if="profileData.invitation_code">
                  <div class="action-link">
                    <a @click="copyInvitationCode">Copy my invitation code: {{ profileData.invitation_code }}</a>
                  </div>
                </template>
              </div>
            </div>
            
            <a-divider class="announcement-divider" />
            
            <div class="announcement-item">
              <gift-outlined />
              <div class="announcement-content">
                Order over  <span class="highlight"> {{ currencyUnit }}{{ convertPrice(FREE_SHIPPING_THRESHOLD) }}</span> can enjoy <span class="highlight">free shipping</span> benefit
                <div class="action-link">
                  <a @click="navigateTo('/')">Shop Now</a>
                </div>
              </div>
            </div>
            
            <a-divider class="announcement-divider" />
            
            <div class="announcement-item">
              <trophy-outlined />
              <div class="announcement-content">
                Member orders can enjoy the <span class="highlight">{{ currencyUnit }}{{ convertPrice(POINTS_EXCHANGE_RATE) }} = 1 point</span> activity, points can be exchanged for<span class="highlight"> coupons</span>
                <div class="action-link">
                  <a @click="navigateTo('/user/points')">View my points</a>
                </div>
              </div>
            </div>
            
            <a-divider class="announcement-divider" v-show="showMoreAnnouncements" />
            
            <div class="announcement-item" v-show="showMoreAnnouncements">
              <shop-outlined />
              <div class="announcement-content">
                Follow our social media, get the latest <span class="highlight">limited time discounts</span> and <span class="highlight">new product releases</span> information
                <div class="action-link">
                  <a href="https://www.instagram.com/hlsclothing" target="_blank">Visit Instagram</a>
                </div>
              </div>
            </div>
            
            <a-divider class="announcement-divider" v-show="showMoreAnnouncements" />
            
            <div class="announcement-item" v-show="showMoreAnnouncements">
              <calendar-outlined />
              <div class="announcement-content">
                All products on the website enjoy <span class="highlight">{{ DISCOUNT_PERCENT }}% off</span>
                <div class="action-link">
                  <a @click="navigateTo('/')">Shop Now</a>
                </div>
              </div>
            </div>
            
            <div class="toggle-more" @click="toggleMoreAnnouncements">
              {{ showMoreAnnouncements ? 'Collapse' : 'View More' }}
              <down-outlined :class="{ 'rotate-icon': showMoreAnnouncements }" />
            </div>
          </div>
        </a-card>
      </a-col>
    </a-row>
    
    <!-- 添加邮箱验证弹窗组件 -->
    <EmailVerification ref="emailVerificationRef" @verified="onEmailVerified" />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed, watch, onUnmounted, nextTick, getCurrentInstance } from 'vue';
import { message } from 'ant-design-vue';
import { useRouter } from 'vue-router';
import PhoneNumberInput from '../../components/PhoneNumberInput.vue';
import EmailVerification from '../../components/EmailVerification.vue';
import { editUserInfo, getUserInfo, userPoints, getMessageList, changeUserAvatar } from '../../api/user';
import { uploadImagesWithBase64 } from '../../api/index';
import Local from '@/utils/local';
import { useCurrencyStore } from '@/store';
import { 
  ShoppingOutlined, 
  StarOutlined, 
  SettingOutlined, 
  DribbbleOutlined, 
  ShoppingCartOutlined, 
  UserOutlined,
  MailOutlined,
  CopyOutlined,
  RightOutlined,
  NotificationOutlined,
  GiftOutlined,
  TrophyOutlined,
  ShopOutlined,
  CalendarOutlined,
  DownOutlined,
  BellOutlined,
  LinkOutlined,
  WalletOutlined,
  TagOutlined
} from '@ant-design/icons-vue';
import { getUserInfo as getCachedUserInfo, saveUserInfo, updateUserInfo, getUserToken } from '@/utils/cache';

const router = useRouter();
const currencyStore = useCurrencyStore();
const { proxy } = getCurrentInstance();

// 邮箱验证弹窗引用
const emailVerificationRef = ref(null);

// 使用ref创建响应式的用户信息数据
const profileData = ref({
  first_name: '',
  last_name: '',
  email: '',
  phone: '',
  gender: 0,
  birthday: null,
  avatar: '',
  // 会员相关信息
  score: 0,
  total_score: 0,
  level: 0,
  followCount: 0,
  memberLevel: '',
  nextLevel: '',
  levelProgress: 0,
  pointsToNextLevel: 0,
  nickname: '',
  username: '',
  money: '0.00',
  invitation_code: ''
});

// 处理手机号和国家代码
const phoneNumber = ref('');
const countryCode = ref('+86');

// 创建一个响应式引用来存储消息列表
const getMessageListFromStorage = () => {
  try {
    const messageList = Local.get('messageList');
    return messageList ? messageList : { total: 0, list: [] };
  } catch (error) {
    console.error(`Error getting messageList from localStorage:`, error);
    return { total: 0, list: [] };
  }
};

const messageListData = ref(getMessageListFromStorage());

// 从缓存中获取消息数量，并监听缓存变化
const messageCount = computed(() => {
  return messageListData.value?.total || 0;
});

// 计算未读消息数量
const unreadMessageCount = computed(() => {
  if (!messageListData.value?.list || !Array.isArray(messageListData.value.list)) {
    return 0;
  }
  // 统计reader_id为null的消息数量，这些是未读消息
  return messageListData.value.list.filter(msg => msg.reader_id === null).length;
});

// 使用货币符号和价格转换
const currencyUnit = computed(() => {
  return currencyStore.currentCurrency?.unit || '$';
});

// 价格转换函数
const convertPrice = (price) => {
  if (proxy && proxy.$ConvertPrice) {
    return proxy.$ConvertPrice(price);
  }
  return price;
};

// 常量设置 - 标准价格
const INVITE_BONUS = 10; // 邀请奖励10美元
const FREE_SHIPPING_THRESHOLD = 99; // 免运费门槛99美元
const POINTS_EXCHANGE_RATE = 10; // 10美元=1积分
const DISCOUNT_PERCENT = 20; // 20%折扣

// 从缓存中获取用户信息
onMounted(() => {
  // 使用新的缓存系统获取用户信息
  const userInfo = getCachedUserInfo() || {};
  
  // 使用ref时，需要使用.value来访问和修改值
  profileData.value = {
    ...profileData.value,
    first_name: userInfo.first_name || '',
    last_name: userInfo.last_name || '',
    email: userInfo.email || '',
    gender: userInfo.gender !== undefined ? userInfo.gender : 0,
    birthday: userInfo.birthday || null,
    avatar: userInfo.avatar || '',
    score: userInfo.score || 0,
    total_score: userInfo.total_score || 0,
    level: userInfo.level || 0,
    followCount: userInfo.followCount || 0,
    memberLevel: userInfo.memberLevel || `Lv${userInfo.level || 0}`,
    nextLevel: userInfo.nextLevel || `Lv${(userInfo.level || 0) + 1}`,
    levelProgress: userInfo.levelProgress || Math.floor(((userInfo.score || 0) / ((userInfo.score || 0) + 100)) * 100),
    pointsToNextLevel: userInfo.pointsToNextLevel || 100,
    nickname: userInfo.nickname || '',
    username: userInfo.username || '',
    money: userInfo.money || '0.00',
    invitation_code: userInfo.invitation_code || ''
  };
  
  // 生成邀请链接
  if (profileData.value.invitation_code) {
    const baseUrl = import.meta.env.VITE_APP_BASE_URL || window.location.origin;
    invitationLink.value = `${baseUrl}/register?code=${profileData.value.invitation_code}`;
  }
  
  // 处理手机号
  if (userInfo.mobile) {
    profileData.value.phone = userInfo.mobile;
    
    // 设置国家代码
    countryCode.value = userInfo.code || '+86';
    phoneNumber.value = userInfo.mobile;
  }
  
  // 检查邮箱验证状态
  if (userInfo) {
    checkEmailVerification(userInfo);
  }
  
  // 初始化消息列表数据 
  fetchMessageList();
  
  // 从服务器获取最新用户信息和消息
  fetchUserInfoAndMessages();
  
  // 设置存储监听器
  setupStorageListener();
  
  // 设置轮询检查
  setupPollingCheck();
});

// 获取消息列表数据
const fetchMessageList = () => {
  // 使用Local工具获取消息列表
  try {
    const parsedData = Local.get('messageList');
    if (parsedData) {
      // 确保消息列表数据结构正确
      messageListData.value = {
        list: Array.isArray(parsedData.list) ? parsedData.list : [],
        total: parsedData.total || 0
      };
    } else {
      // 如果数据不存在，设置默认值
      messageListData.value = { total: 0, list: [] };
    }
  } catch (error) {
    console.error('Failed to parse message list data:', error);
    // 发生错误时设置默认值
    messageListData.value = { total: 0, list: [] };
  }
};

// 获取用户消息列表
const fetchUserMessages = async () => {
  try {
    const messageRes = await getMessageList({
      page: 1,
      page_size: 10
    });
    if (messageRes && messageRes.code === 200) {
      // 确保result.data是数组
      const messageList = Array.isArray(messageRes.result.data) ? messageRes.result.data : [];
      
      // 更新消息列表缓存
      const messageData = {
        list: messageList,
        total: messageRes.result.total || messageList.length
      };
      Local.set('messageList', messageData);
      
      // 更新当前页面的消息数据
      messageListData.value = messageData;
    }
  } catch (error) {
    console.error('Failed to fetch user messages:', error);
  }
};

// 监听本地存储变化的函数
const setupStorageListener = () => {
  window.addEventListener('storage', (event) => {
    if (event.key === 'messageList') {
      try {
        if (event.newValue) {
          // 尝试使用JSON.parse解析数据，出错时回退到使用Local.get
          try {
            const newMessageList = JSON.parse(event.newValue);
            messageListData.value = newMessageList;
          } catch (parseError) {
            // 如果解析失败，则直接使用Local.get获取数据
            const newMessageList = Local.get('messageList');
            if (newMessageList) {
              messageListData.value = newMessageList;
            }
          }
        }
      } catch (error) {
        console.error('Failed to handle message list data:', error);
      }
    }
  });
};

// 定期检查本地存储中的消息列表是否有更新
const setupPollingCheck = () => {
  const checkInterval = setInterval(() => {
    try {
      const currentMessageList = Local.get('messageList');
      if (currentMessageList) {
        // 使用深度比较确保数据真的变化了
        if (JSON.stringify(currentMessageList) !== JSON.stringify(messageListData.value)) {
          // 直接替换整个对象，确保响应式更新
          messageListData.value = JSON.parse(JSON.stringify(currentMessageList));
        }
      }
    } catch (error) {
      console.error('Failed to check message list updates:', error);
    }
  }, 5000); // 每5秒检查一次
  
  // 组件卸载时清除定时器
  onUnmounted(() => {
    clearInterval(checkInterval);
  });
};

// 更新手机号数据
const updatePhoneData = (phoneData) => {
  if (phoneData) {
    // 即使手机号无效，也保存当前输入的值
    if (phoneData.isValid) {
      profileData.value.phone = phoneData.data.phoneNumber;
      countryCode.value = phoneData.data.countryCode;
    } else {
      // 即使无效也保存当前输入的值，确保用户输入不会丢失
      profileData.value.phone = phoneData.data.phoneNumber;
      countryCode.value = phoneData.data.countryCode;
    }
  }
};

// 保存个人资料
const saveProfile = () => {
  // 保存到本地存储
  const userInfoToSave = {
    last_name: profileData.value.last_name,
    first_name: profileData.value.first_name,
    mobile: profileData.value.phone,
    code: countryCode.value,
    email: profileData.value.email,
    birthday: profileData.value.birthday,
    gender: profileData.value.gender,
    // avatar now handled separately by changeUserAvatar
  };
  
  editUserInfo(userInfoToSave).then(res => {
    console.log(res);
    if (res.code === 200) {
      message.success('Profile information saved successfully');
      
      // 更新新的缓存系统
      const userInfo = getCachedUserInfo() || {};
      const updatedInfo = {
        ...userInfo,
        last_name: profileData.value.last_name,
        first_name: profileData.value.first_name,
        mobile: profileData.value.phone,
        code: countryCode.value,
        email: profileData.value.email,
        birthday: profileData.value.birthday,
        gender: profileData.value.gender
      };
      
      // 使用新系统的更新方法
      updateUserInfo(updatedInfo);
      
      // 无感获取用户信息和消息列表
      fetchUserInfoAndMessages();
    } else {
      message.error('Failed to save profile information');
    }
  }).catch(error => {
    message.error('Failed to save profile information');
  });
};

// 无感获取用户信息和消息列表
const fetchUserInfoAndMessages = async () => {
  try {
    // 获取用户完整信息 - 使用 getUserInfo API
    try {
      const userRes = await getUserInfo();
      if (userRes && userRes.code === 200) {
        // 获取当前用户缓存
        const userInfo = getCachedUserInfo() || {};
        
        // 更新用户个人资料
        if (userRes.result) {
          // 创建更新对象
          const updatedInfo = {
            ...userInfo,
            first_name: userRes.result.first_name || userInfo.first_name,
            last_name: userRes.result.last_name || userInfo.last_name,
            mobile: userRes.result.mobile || userInfo.mobile,
            code: userRes.result.code || userInfo.code,
            email: userRes.result.email || userInfo.email,
            birthday: userRes.result.birthday || userInfo.birthday,
            avatar: userRes.result.avatar || userInfo.avatar,
            gender: userRes.result.gender !== undefined ? userRes.result.gender : userInfo.gender
          };
          
          // 更新邀请码 - 无论是否为null都更新
          if (userRes.result.hasOwnProperty('invitation_code')) {
            updatedInfo.invitation_code = userRes.result.invitation_code;
            // 更新当前页面数据
            profileData.value.invitation_code = userRes.result.invitation_code;
            // 更新邀请链接
            if (userRes.result.invitation_code) {
              const baseUrl = import.meta.env.VITE_APP_BASE_URL || window.location.origin;
              invitationLink.value = `${baseUrl}/register?code=${userRes.result.invitation_code}`;
            } else {
              // 清空邀请链接
              invitationLink.value = '';
            }
          }
          
          // 更新到缓存
          saveUserInfo(updatedInfo);
          
          // 更新当前页面数据
          profileData.value.birthday = userRes.result.birthday || profileData.value.birthday;
        }
      }
    } catch (error) {
      console.error('Failed to fetch user info:', error);
    }
    
    // 获取用户积分信息 - 使用 userPoints API
    try {
      const res = await userPoints();
      if (res && res.code === 200) {
        // 更新缓存中的积分和历史积分
        const userInfo = getCachedUserInfo() || {};
        if (userInfo) {
          // 使用新的缓存系统更新用户信息
          updateUserInfo({ 
            score: res.result.score,
            total_score: res.result.total_score
          });
          
          // 更新页面的用户信息数据
          profileData.value.score = res.result.score;
          profileData.value.total_score = res.result.total_score;
        }
      }
    } catch (error) {
      console.error('Failed to fetch user points:', error);
    }

    // 获取用户消息列表 - 使用新的fetchUserMessages方法
    await fetchUserMessages();
    
  } catch (error) {
    console.error('Error in fetchUserInfoAndMessages:', error);
  }
};


// 重置表单
const resetForm = () => {
  const userInfo = getCachedUserInfo();
  if (userInfo) {
    // 使用ref时，需要整体替换.value的内容
    profileData.value = {
      ...profileData.value,
      first_name: userInfo.first_name,
      last_name: userInfo.last_name,
      email: userInfo.email,
      gender: userInfo.gender !== undefined ? userInfo.gender : 0,
      birthday: userInfo.birthday,
      avatar: userInfo.avatar,
      score: userInfo.score,
      total_score: userInfo.total_score,
      level: userInfo.level,
      followCount: userInfo.followCount || 0,
      memberLevel: userInfo.memberLevel || `Lv${userInfo.level}`,
      nextLevel: userInfo.nextLevel || `Lv${userInfo.level + 1}`,
      levelProgress: userInfo.levelProgress || Math.floor((userInfo.score / (userInfo.score + 100)) * 100),
      pointsToNextLevel: userInfo.pointsToNextLevel || 100,
      nickname: userInfo.nickname,
      username: userInfo.username,
      money: userInfo.money,
      invitation_code: userInfo.invitation_code,
      phone: userInfo.mobile
    };
    
    // 重置手机号和国家代码
    countryCode.value = userInfo.code;
    phoneNumber.value = userInfo.mobile;
  }
  message.info('Form has been reset');
};

// 导航到其他页面
const navigateTo = (path) => {
  router.push(path);
};

// 头像上传前检查
const beforeUpload = (file) => {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
  if (!isJpgOrPng) {
    message.error('Only JPG or PNG format images can be uploaded!');
  }
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    message.error('The image must be less than 2MB!');
  }
  return isJpgOrPng && isLt2M;
};

// 自定义上传头像函数
const uploadAvatar = async (options) => {
  try {
    const { file, onSuccess, onError, onProgress } = options;
    
    // 显示加载状态
    const loadingKey = 'uploading_avatar';
    message.loading({ content: 'Uploading...', key: loadingKey, duration: 0 });
    
    // 使用 uploadImagesWithBase64 工具上传图片
    const uploadResult = await uploadImagesWithBase64([file], {
      maxSize: 2, // 最大2MB
      maxCount: 1, // 只上传一张图片
    }, (index, progress) => {
      // 可以处理进度回调
      onProgress({ percent: progress });
    });
    
    // 获取上传结果的URL
    if (uploadResult && uploadResult.length > 0 && uploadResult[0].response.url) {
      const avatarUrl = uploadResult[0].response.url;
      
      // 调用后端API更新头像
      const res = await changeUserAvatar({ avatar: avatarUrl });
      
      if (res.code === 200) {
        // 更新本地状态
        profileData.value.avatar = avatarUrl;
        
        // 更新缓存 - 使用新缓存系统
        updateUserInfo({ avatar: avatarUrl });
        
        message.success({ content: 'Avatar updated successfully', key: loadingKey });
        onSuccess(uploadResult[0].response);
      } else {
        message.error({ content: 'Failed to update avatar', key: loadingKey });
        onError('Failed to update avatar');
      }
    } else {
      message.error({ content: 'Failed to upload image', key: loadingKey });
      onError('Failed to upload image');
    }
  } catch (error) {
    console.error('Avatar upload error:', error);
    message.error('Failed to upload avatar: ' + (error.message || 'Unknown error'));
    options.onError('Failed to upload avatar');
  }
};

// 检查用户邮箱验证状态
const checkEmailVerification = (userInfo) => {
  if (userInfo && userInfo.is_email === 0) {
    // 延迟显示弹窗，确保组件已经挂载
    nextTick(() => {
      emailVerificationRef.value?.show();
    });
  }
};

// 邮箱验证成功回调
const onEmailVerified = () => {
  message.success('Email verification successful, you can now fully use all features');
  
  // 更新缓存，使用新系统
  updateUserInfo({ is_email: 1 });
};

// 复制邀请码
const copyInvitationCode = () => {
  if (profileData.value.invitation_code) {
    // 创建临时元素
    const textArea = document.createElement('textarea');
    textArea.value = profileData.value.invitation_code;
    document.body.appendChild(textArea);
    textArea.select();
    
    try {
      // 尝试使用浏览器复制API
      document.execCommand('copy');
      message.success('Invitation code copied successfully');
    } catch (err) {
      console.error('Copy failed:', err);
      message.error('Copy failed, please copy manually');
    } finally {
      // 移除临时元素
      document.body.removeChild(textArea);
    }
  }
};

// 添加邀请链接显示
const invitationLink = ref('');

// 监听邀请码变化，更新邀请链接
watch(() => profileData.value.invitation_code, (newCode) => {
  if (newCode) {
    const baseUrl = import.meta.env.VITE_APP_BASE_URL || window.location.origin;
    invitationLink.value = `${baseUrl}/register?code=${newCode}`;
  } else {
    invitationLink.value = '';
  }
});

// 复制邀请链接
const copyInvitationLink = () => {
  if (invitationLink.value) {
    // 创建临时元素
    const textArea = document.createElement('textarea');
    textArea.value = invitationLink.value;
    document.body.appendChild(textArea);
    textArea.select();
    
    try {
      // 尝试使用浏览器复制API
      document.execCommand('copy');
      message.success('Invitation link copied successfully');
    } catch (err) {
      console.error('Copy failed:', err);
      message.error('Copy failed, please copy manually');
    } finally {
      // 移除临时元素
      document.body.removeChild(textArea);
    }
  }
};

// 显示更多公告的逻辑
const showMoreAnnouncements = ref(false);
const toggleMoreAnnouncements = () => {
  showMoreAnnouncements.value = !showMoreAnnouncements.value;
};

// 获取Token用于鉴权
const getToken = () => {
  return getUserToken() || '';
};
</script>

<style scoped>
.profile-container {
  padding: 0 10px;
}

.user-info-card {
  margin-bottom: 16px;
}

/* 性别选择样式 */
:deep(.ant-radio-wrapper) {
  color: #595959;
  
  &:hover {
    .ant-radio {
      .ant-radio-inner {
        border-color: #262626;
      }
    }
  }
  
  .ant-radio {
    .ant-radio-inner {
      border-color: #d9d9d9;
      transition: all 0.3s;
      
      &::after {
        background-color: #262626;
      }
    }
    
    &.ant-radio-checked {
      .ant-radio-inner {
        border-color: #262626;
        background-color: #fff;
      }
      
      &::after {
        border-color: #262626;
      }
    }
  }
  
  &:where(.ant-radio-wrapper-checked) {
    color: #262626;
  }
  
  &:hover {
    color: #262626;
  }
}

/* 禁用输入框样式 */
.disabled-input {
  background-color: #f5f5f5;
  color: #595959;
}

.user-header {
  display: flex;
  flex-direction: column;
  align-items: center;
  text-align: center;
  margin-bottom: 16px;
}

.user-basic-info {
  margin-top: 16px;
}

.member-badge {
  margin-top: 8px;
}

.user-stats {
  display: flex;
  justify-content: space-around;
  text-align: center;
  margin: 16px 0;
}

.stat-item {
  flex: 1;
}

.stat-value {
  font-size: 20px;
  font-weight: bold;
  margin-bottom: 4px;
}

.stat-label {
  color: rgba(0, 0, 0, 0.45);
}

.quick-links {
  margin: 16px 0;
}

/* 按钮样式 */
:deep(.ant-btn-primary) {
  background: #262626;
  border-color: #262626;
  
  &:hover {
    background: #434343;
    border-color: #434343;
  }
  
  &:active {
    background: #000;
    border-color: #000;
  }
}

.ml-10 {
  margin-left: 10px;
}

.avatar-upload {
  display: flex;
  align-items: center;
}

/* 媒体查询适配 */
@media (max-width: 1280px) {
  .user-header {
    flex-direction: column;
  }
  
  .avatar-upload {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .avatar-upload .ml-10 {
    margin-left: 0;
    margin-top: 10px;
  }
  
  .user-stats {
    flex-direction: row;
    flex-wrap: wrap;
  }
  
  .stat-item {
    flex: 0 0 33.33%;
    margin-bottom: 10px;
  }
  
  .ml-10 {
    margin-left: 10px;
  }
  
  /* 在小屏幕上调整表单按钮 */
  @media (max-width: 576px) {
    .ml-10 {
      margin-left: 0;
      margin-top: 10px;
    }
    
    a-form-item :wrapper-col {
      text-align: center;
    }
  }
}

.invitation-code-section {
  margin-bottom: 16px;
}

.invitation-code-title {
  margin-bottom: 8px;
}

.invitation-code-title h3 {
  color: #333;
  font-size: 16px;
  margin: 0;
}

.invitation-code-display {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

.code-value {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
  background-color: #f7f7f7;
  padding: 8px 12px;
  border-radius: 4px;
  width: 100%;
  border: 1px solid #e0e0e0;
}

.code-value h2 {
  margin: 0;
  margin-right: 8px;
  color: #333;
  font-weight: bold;
  flex: 1;
}

.invitation-code-section .ant-btn-link {
  padding-left: 0;
  color: #555;
}

.empty-code {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 100%;
  padding: 16px;
  background-color: #f7f7f7;
  border-radius: 4px;
  border: 1px solid #e0e0e0;
}

.empty-code p {
  margin-bottom: 8px;
  color: #666;
}

.invitation-link-section {
  margin: 12px 0 16px 0;
}

.link-header {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.link-header h4 {
  margin: 0;
  margin-right: 8px;
  color: #333;
  font-size: 15px;
}

.link-value {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
  background-color: #f7f7f7;
  padding: 8px 12px;
  border-radius: 4px;
  width: 100%;
  border: 1px dashed #d9d9d9;
}

.link-value p {
  margin: 0;
  margin-right: 8px;
  color: #333;
  font-size: 14px;
  flex: 1;
  word-break: break-all;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.invitation-link-section .ant-btn-link {
  padding-left: 0;
  color: #555;
}

.code-value a-button:hover,
.link-value a-button:hover {
  opacity: 0.8;
}

.invitation-code-section .ant-btn-link:hover,
.invitation-link-section .ant-btn-link:hover {
  color: #222;
}

.announcement-card {
  margin-top: 16px;
}

.announcements-container {
  padding: 0;
}

.announcement-item {
  display: flex;
  align-items: flex-start;
  margin-bottom: 12px;
  padding: 0 8px;
  transition: opacity 0.3s, transform 0.3s;
}

.announcement-item:hover {
  transform: translateX(3px);
}

.announcement-item :deep(svg) {
  font-size: 20px;
  color: #555;
  margin-top: 2px;
}

.announcement-content {
  margin-left: 12px;
  font-size: 14px;
  line-height: 1.6;
  color: #555;
}

.highlight {
  font-weight: bold;
  color: #262626;
}

.announcement-divider {
  margin: 12px 0;
  border-top: 1px dashed #e8e8e8;
}

.announcement-card :deep(.ant-card-head) {
  border-bottom: 1px solid #f0f0f0;
  padding: 0 24px;
}

.announcement-card :deep(.ant-card-head-title) {
  font-size: 16px;
  font-weight: bold;
  color: #262626;
}

.action-link {
  margin-top: 8px;
  color: #555;
}

.action-link a {
  color: #555;
  text-decoration: none;
  transition: color 0.3s;
  display: inline-flex;
  align-items: center;
}

.action-link a:hover {
  color: #262626;
}

.action-link a:after {
  content: '→';
  margin-left: 4px;
  transition: transform 0.3s;
}

.action-link a:hover:after {
  transform: translateX(3px);
}

.toggle-more {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-top: 16px;
  cursor: pointer;
  padding: 8px 0;
  color: #555;
  font-size: 14px;
  transition: color 0.3s;
  user-select: none;
}

.toggle-more:hover {
  color: #262626;
}

.toggle-more svg {
  margin-left: 4px;
  transition: transform 0.3s;
}

.rotate-icon {
  transform: rotate(180deg);
}
</style>